package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
        loadServlet(new File(appBase), 0, null);


        // 定义一个线程池
        // 核心线程数
        int corePoolSize = 10;
        // 最大线程数
        int maximumPoolSize = 50;
        // 存活时间
        long keepAliveTime = 100L;
        // 时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        // 储存方式
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        // 工厂
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        // 拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );


        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*
            多线程改造（使用线程池）
         */
        while (true) {
            Socket socket = serverSocket.accept();

            RequestProcessor requestProcessor = new RequestProcessor(socket, contextMap);
            threadPoolExecutor.execute(requestProcessor);
        }


    }

    private HashMap<String, Context> contextMap = new HashMap<>();

    public static String appBase = "C:/Users/webapps";

    /**
     * 加载解析web.xml，初始化Servlet
     *
     * @param dir
     * @param project
     */
    private void doLoadServlet(File dir, String project) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = new FileInputStream(dir);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            HashMap<String, HttpServlet> servletMap = new HashMap<>();
            // 创建项目的classloard
            URL url = new URL("file:" + appBase + "/" + project + "/");
            ClassLoader loader = new URLClassLoader(new URL[]{url});
            ClassLoader parent = loader.getParent();

            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                Class<?> clazz = loader.loadClass(servletClass);//自己定义的loader路径可以找到
                HttpServlet httpServlet = (HttpServlet)clazz.newInstance();
                servletMap.put(urlPattern,(HttpServlet) httpServlet);
            }

            Context context = new Context();
            context.setServletMap(servletMap);
            context.setPrefix("/" + project);
            contextMap.put(project, context);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }

    public void loadServlet(File dir, int index, String project) {
        index++;
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                // 保存根项目名
                if (index == 1) {
                    project = children[i];
                }

                loadServlet(new File(dir, children[i]), index, project);
            }
        } else {
            if (index == 1) {
                throw new RuntimeException("部署目录不能是文件路径");
            }
            String name = dir.getName();
            if ("web.xml".equals(name)) {
                doLoadServlet(dir, project);
            }
        }
    }

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }






    }




}
